package com.bcmusic.user.controller;

import com.bcmusic.file.feign.FileFeign;
import com.bcmusic.user.config.TokenDecode;
import com.bcmusic.user.pojo.*;
import com.bcmusic.user.service.*;
import com.github.pagehelper.PageInfo;
import entity.Result;
import entity.StatusCode;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.swing.text.TabExpander;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/****
 * @Author:admin
 * @Description:
 * @Date 2019/6/14 0:18
 *****/

@RestController
@RequestMapping("/user")
@Api("用户模块")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private TokenDecode tokenDecode;

    @Autowired
    private FileFeign fileFeign;

    @Autowired
    private DistributorIdentificationService distributorIdentificationService;
    @Autowired
    private EnterpriseIdentificationService enterpriseIdentificationService;
    @Autowired
    private MusicianIdentificationService musicianIdentificationService;
    @Autowired
    private UserIdentificationService userIdentificationService;
    /***
     * User分页条件搜索实现
     * @param user
     * @param page
     * @param size
     * @return
     */
    @PostMapping(value = "/search/{page}/{size}")
    public Result<PageInfo> findPage(@RequestBody(required = false) User user, @PathVariable int page, @PathVariable int size) {
        //调用UserService实现分页条件查询User
        PageInfo<User> pageInfo = userService.findPage(user, page, size);
        return new Result(true, StatusCode.OK, "查询成功", pageInfo);
    }

    /***
     * User分页搜索实现
     * @param page:当前页
     * @param size:每页显示多少条
     * @return
     */
    @GetMapping(value = "/search/{page}/{size}")
    public Result<PageInfo> findPage(@PathVariable int page, @PathVariable int size) {
        //调用UserService实现分页查询User
        PageInfo<User> pageInfo = userService.findPage(page, size);
        return new Result<PageInfo>(true, StatusCode.OK, "查询成功", pageInfo);
    }

    /***
     * 多条件搜索品牌数据
     * @param user
     * @return
     */
    @PostMapping(value = "/search")
    public Result<List<User>> findList(@RequestBody(required = false) User user) {
        //调用UserService实现条件查询User
        List<User> list = userService.findList(user);
        return new Result<List<User>>(true, StatusCode.OK, "查询成功", list);
    }

    /***
     * 根据ID删除品牌数据
     * @param id
     * @return
     */
    @DeleteMapping(value = "/{id}")
    public Result delete(@PathVariable Integer id) {
        //调用UserService实现根据主键删除
        userService.delete(id);
        return new Result(true, StatusCode.OK, "删除成功");
    }

    /***
     * 修改User数据
     * @param user
     * @param id
     * @return
     */
    @PutMapping(value = "/{id}")
    public Result update(@RequestBody User user, @PathVariable Integer id) {
        //设置主键值
        user.setUserId(id);
        //调用UserService实现修改User
        userService.update(user);
        return new Result(true, StatusCode.OK, "修改成功");
    }

    /***
     * 新增User数据
     * @param user
     * @return
     */
    @PostMapping
    public Result add(@RequestBody User user) {
        //调用UserService实现添加User
        userService.add(user);
        return new Result(true, StatusCode.OK, "添加成功");
    }

    /***
     * 根据ID查询User数据
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result<User> findById(@PathVariable Integer id) {

        //调用UserService实现根据主键查询User
        User user = userService.findById(id);
        return new Result<User>(true, StatusCode.OK, "查询成功", tokenDecode.getUserInfo());
    }

    /***
     * 查询User全部数据
     * @return
     */
    @GetMapping
    public Result<List<User>> findAll() {
        Map<String, String> userInfo = tokenDecode.getUserInfo();
        //调用UserService实现查询所有User
        List<User> list = userService.findAll();
        return new Result<List<User>>(true, StatusCode.OK, "查询成功", list);
    }

    /**
     * 根据手机查询用户，后台调用
     *
     * @param phone
     * @return
     */
    @ApiIgnore
    @GetMapping("/findUser/{phone}")
    public Result<User> findUserByPhone(@PathVariable("phone")String phone) {
        User user = new User();
        user.setUserPhone(phone);

        List<User> list = userService.findList(user);
        if(list.isEmpty())
        {
            return new Result<User>(true, StatusCode.ERROR, "查找失败", null);
        }
        user=list.get(0);
        return new Result<User>(true, StatusCode.OK, "查找成功", user);
    }

    /**
     * 发送短信验证码
     *
     * @param phone
     * @return
     */
    @PostMapping("register/getVerificationCode")
    public Result<Integer> getVerificationCode(@RequestParam("phone") @ApiParam(name = "phone",value = "手机号",required = true)  String phone) {
        if (phone == null) {
            return new Result<>(true, StatusCode.ERROR, "手机号码为空");
        }
        String verificationCode = userService.getVerificationCode(phone);

        //放入redis，设置三分钟过期时间
//        redisTemplate.opsForValue().set("verificationCode_" + phone, verificationCode, 3, TimeUnit.MINUTES);
        redisTemplate.boundHashOps("verificationCode").put(phone,verificationCode);
        return new Result<>(true, StatusCode.OK, "验证码发送成功");
    }


    /**
     * 校验验证码是否正确
     *
     * @param phone
     * @return
     */
    @PostMapping("register/verifyCode")
    public Result<Integer> verifyCode(@RequestParam("phone") @ApiParam(name = "phone",value = "手机号",required = true)  String phone, @ApiParam(name = "code",value = "验证码",required = true)@RequestParam("code") String code) {
        String verificationCode =(String) redisTemplate.boundHashOps("verificationCode").get(phone);

        if (code.equals(verificationCode)) {
            return new Result<>(true, StatusCode.OK, "验证码成功");
        }
        return new Result<>(true, StatusCode.ERROR, "验证验证码错误");
    }

    /**
     * 验证手机号是否被注册
     *
     * @param phone
     * @return
     */
    @PostMapping("register/verify")
    public Result<Integer> verifyPhone(@RequestParam("phone") @ApiParam(name = "phone",value = "手机号",required = true) String phone) {
        User user = new User();
        user.setUserPhone(phone);
        List<User> list = userService.findList(user);
        if (!list.isEmpty()) {
            return new Result<>(true, StatusCode.ERROR, "该手机号已经注册，请直接前往登录");
        }
        System.out.println("调用成功");
        return new Result<>(true, StatusCode.OK, "手机号可用");
    }

    /**
     * 处理注册表单
     * @param user
     * @return
     */
    @PostMapping("register")
    public Result<User> register(@RequestBody  User user) {
        User newUser = userService.add(user);
        if (user.getUserId() == null) {
            return new Result<>(true, StatusCode.ERROR, "注册失败");
        }
        return new Result<>(true, StatusCode.OK, "注册成功", newUser);
    }

    /**
     *
     * 查询用户类型
     * @return
     */
    @PostMapping("getUserType")
    public Result<Integer>getUserType()
    {
        String userNum = tokenDecode.getUserInfo().get("id");
        User user = userService.findUserByNum(userNum);
        return new Result<>(true,StatusCode.OK,"查询成功",user.getUserType());
    }


    /**
     * 更改用户头像(普通用户)
     * @return
     */
    @PostMapping("updatePhoto")
    public Result<User> updatePhoto(@RequestParam MultipartFile file)
    {
        if(file.isEmpty())
        {
            return new Result<>(true,StatusCode.ERROR,"更改头像失败，请重新选择文件");
        }
        String userNum = tokenDecode.getUserInfo().get("id");
        User user = userService.findUserByNum(userNum);
        if(user==null)
        {
            return new Result<>(true,StatusCode.ERROR,"获取认证信息失败");
        }
        String upload = fileFeign.upload(file);
        switch (user.getUserType()){
            case 0:
                return new Result<>(true,StatusCode.ERROR,"您未认证，请认证之后重试");
            case 1:
                MusicianIdentification musicianIdentification=new MusicianIdentification();
                musicianIdentification.setIdentificationId(user.getUserIdentiId());
                musicianIdentification.setProfilePhoto(upload);
                return new Result<>(true,StatusCode.OK,"修改成功",musicianIdentificationService.updateSelective(musicianIdentification));
            case 2:
                EnterpriseIdentification enterpriseIdentification=new EnterpriseIdentification();
                enterpriseIdentification.setIdentificationId(user.getUserIdentiId());
                enterpriseIdentification.setProfilePhoto(upload);
                return new Result<>(true,StatusCode.OK,"修改成功",enterpriseIdentificationService.updateSelective(enterpriseIdentification));
            case 3:
                DistributorIdentification distributorIdentification=new DistributorIdentification();
                distributorIdentification.setIdentificationId(user.getUserIdentiId());
                distributorIdentification.setProfilePhoto(upload);
                return new Result<>(true,StatusCode.OK,"修改成功",distributorIdentificationService.updateSelective(distributorIdentification));
            case 5:
                UserIdentification userIdentification=new UserIdentification();
                userIdentification.setIdentificationId(userIdentification.getIdentificationId());
                userIdentification.setProfilePhoto(upload);
                return new Result<>(true,StatusCode.OK,"修改成功",userIdentificationService.updateSelective(userIdentification));
            default:
                return new Result<>(true,StatusCode.ERROR,"更改头像失败");
        }
    }

    /**
     * 获取用户头像
     * @return
     */
    @GetMapping("getUserPhoto")
    public Result<String> getUserPhoto()
    {
//        String type = tokenDecode.getUserInfo().get("authorities");
        String userNum = tokenDecode.getUserInfo().get("id");
        User user = userService.findUserByNum(userNum);
        if(user==null)
        {
            return new Result<>(true,StatusCode.ERROR,"获取头像");
        }
        String photo=null;
        switch (user.getUserType()){
            case 0:
                return new Result<>(true,StatusCode.ERROR,"您未认证，请认证之后重试");
            case 1:
                MusicianIdentification musicianIdentification=new MusicianIdentification();
                photo=musicianIdentificationService.findById(user.getUserIdentiId()).getProfilePhoto();
                break;
            case 2:
                EnterpriseIdentification enterpriseIdentification=new EnterpriseIdentification();
                photo=enterpriseIdentificationService.findById(user.getUserIdentiId()).getProfilePhoto();
                break;
            case 3:
                DistributorIdentification distributorIdentification=new DistributorIdentification();
                photo=distributorIdentificationService.findById(user.getUserIdentiId()).getProfilePhoto();
                break;
            case 5:
                UserIdentification userIdentification=new UserIdentification();
                photo=userIdentificationService.findById(user.getUserIdentiId()).getProfilePhoto();
                break;
            default:
                return new Result<>(true,StatusCode.ERROR,"获取头像失败");
        }
        if(StringUtils.isEmpty(photo))
        {
            return new Result<>(true,StatusCode.ERROR,"获取头像失败");
        }
        return new Result<>(true,StatusCode.OK,"查询成功",photo);

    }


    /**
     * 获取用户手机号以及昵称
     * @return
     */
    @GetMapping("getUserBasicInfo")
    public Result<HashMap> getUserBasicInfo()
    {
        String userNum = tokenDecode.getUserInfo().get("id");
        User user=new User();
        user.setUserNumber(userNum);
        user = userService.findUserByNum(userNum);
        if(user==null)
        {
            return new Result<>(true,StatusCode.ERROR,"查询失败");
        }
        Map<String,String> map=new HashMap<>();
        map.put("nickName",user.getNickName());
        map.put("phone",user.getUserPhone());
        return new Result<>(true,StatusCode.OK,"查询成功",map);

    }

    /**
     * 获取认证信息，这个可以跟获取头像的合并，但是前端业务需要就只能再写一次
     * @return
     */
    @GetMapping("getUserIdentificationInfo")
    public Result getUserIdentificationInfo()
    {
        String userNum = tokenDecode.getUserInfo().get("id");

        User user = userService.findUserByNum(userNum);
        if(user==null)
        {
            return new Result<>(true,StatusCode.ERROR,"获取认证信息失败");
        }
        switch (user.getUserType()){
            case 0:
                return new Result<>(true,StatusCode.ERROR,"您未认证，请认证之后重试");
            case 1:
                MusicianIdentification musicianIdentification=new MusicianIdentification();
                return new Result(true,StatusCode.OK,"查询成功",musicianIdentificationService.findById(user.getUserIdentiId()));
            case 2:
                EnterpriseIdentification enterpriseIdentification=new EnterpriseIdentification();
                return new Result(true,StatusCode.OK,"查询成功",enterpriseIdentificationService.findById(user.getUserIdentiId()));
            case 3:
                DistributorIdentification distributorIdentification=new DistributorIdentification();
                return new Result(true,StatusCode.OK,"查询成功",distributorIdentificationService.findById(user.getUserIdentiId()));
            case 5:
                UserIdentification userIdentification=new UserIdentification();
                return new Result(true,StatusCode.OK,"查询成功",userIdentificationService.findById(user.getUserIdentiId()));
            default:
                return new Result<>(true,StatusCode.ERROR,"获取认证信息失败");
        }
    }


    /**
     * 获取其认证姓名或者公司名称
     * @return
     */
    @GetMapping("/getRealName")
    public Result getRealName()
    {
        String userNum = tokenDecode.getUserInfo().get("id");
        User user = userService.findUserByNum(userNum);
        if(user==null)
        {
            return new Result<>(true,StatusCode.ERROR,"获取认证信息失败");
        }
        switch (user.getUserType()){
            case 0:
                return new Result<>(true,StatusCode.ERROR,"您未认证，请认证之后重试");
            case 1:
                return new Result(true,StatusCode.OK,"查询成功",musicianIdentificationService.findById(user.getUserIdentiId()).getMusicianName());
            case 2:
                return new Result(true,StatusCode.OK,"查询成功",enterpriseIdentificationService.findById(user.getUserIdentiId()).getEnterpriseName());
            case 3:
                return new Result(true,StatusCode.OK,"查询成功",distributorIdentificationService.findById(user.getUserIdentiId()).getDistributorName());
            case 5:
                return new Result(true,StatusCode.OK,"查询成功",userIdentificationService.findById(user.getUserIdentiId()).getUserOrdinaryName());
            default:
                return new Result<>(true,StatusCode.ERROR,"获取认证信息失败");
        }
    }

    @ApiIgnore
    @PostMapping("/getRealNameList")
    public Result<List<String>> getRealNameList(@RequestParam("userNumList") List<String>userNumList){
        if(userNumList.size()==0)
        {
            return new Result(true,StatusCode.ERROR,"查询失败");
        }
        List<String>realNameList=new ArrayList<>();
        for (int i = 0; i < userNumList.size(); i++) {
            String userNum = userNumList.get(i);
            User user = userService.findUserByNum(userNum);
            if(user==null)
            {
                realNameList.add(new String("匿名用户"));
            }
            switch (user.getUserType()){
                case 0:
                    realNameList.add(new String("匿名用户"));
                    break;
                case 1:
                    realNameList.add(musicianIdentificationService.findById(user.getUserIdentiId()).getMusicianName());
                    break;
                case 2:
                    realNameList.add(enterpriseIdentificationService.findById(user.getUserIdentiId()).getEnterpriseName());
                    break;
                case 3:
                    realNameList.add(distributorIdentificationService.findById(user.getUserIdentiId()).getDistributorName());
                    break;
                case 5:
                    realNameList.add(userIdentificationService.findById(user.getUserIdentiId()).getUserOrdinaryName());
                default:
                    realNameList.add("匿名用户");
                    break;
            }
        }
        return new Result(true,StatusCode.OK,"查询成功",realNameList);
    }
}
